package com.example.weight.wormHandle.garbageDisposal.researchDevelopment;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.weight.R;
import com.example.weight.arrayAdapter.Item;
import com.example.weight.arrayAdapter.ItemAdapter;
import com.example.weight.config.Config;
import com.example.weight.util.WeightActivity;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;

public class IncomingSceneFeed extends AppCompatActivity implements View.OnClickListener{
    private String name, factory;
    private TitleBar titleBar;
    private String deviceName;

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");// HH:mm:ss
    Date incomingDate = new Date(System.currentTimeMillis());
    private TextView feed_date;
    private List<BatchGroupNumber> batchGroupNumberList;
    private Spinner batchGroupNumber;
    private int belongTo_id;
    private List<String> deviceNameList;
    private Spinner deviceName_3;
    private TextView feed_start;
    private Button btn_feed_start;
    private Button btn_feed_end;
    private TextView feed_end;
    private TextView income_weight;
    private TextView breed_box_weight;
//    private TextView target_weight;
//        private TextView reality_weight;
    private TextView cultivate_box_weight;
        private TextView insect_residus_box_weight;
//    private TextView insect_residus_weight;

    private EditText remark;

    String activeButton = new String();
    Calendar calendar= Calendar.getInstance(Locale.CHINA);
    private TextWatcher weightChange_watcher;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Intent previousIntent = getIntent();
        name = previousIntent.getStringExtra("name");
        factory = previousIntent.getStringExtra("factory");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.incoming_scene_feed);

        titleBar=findViewById(R.id.titleBar);
        titleBar.setOnTitleBarListener(new OnTitleBarListener() {

            @Override
            public void onLeftClick(View v) {
                IncomingSceneFeed.this.finish();
            }

            @Override
            public void onTitleClick(View v) {
            }
            @Override
            public void onRightClick(View v) {
            }
        });

        batchGroupNumberList = new ArrayList<>();
        feed_date = findViewById(R.id.incoming_scene_feedDate);
        feed_date.setText(simpleDateFormat.format(incomingDate));
        deviceNameList = new ArrayList<>();
        deviceName_3 = findViewById(R.id.incoming_scene_deviceName_3);
        batchGroupNumber = findViewById(R.id.batch_group_number_list);
        income_weight = findViewById(R.id.income_weight);

        feed_start = (TextView) findViewById(R.id.feed_start);
        feed_start.setOnClickListener(this);
        feed_end = (TextView) findViewById(R.id.feed_end);
        feed_end.setOnClickListener(this);


        btn_feed_start = findViewById(R.id.btn_feed_start);
        btn_feed_end = findViewById(R.id.btn_feed_end);
        btn_feed_start.setOnClickListener(this);
        btn_feed_end.setOnClickListener(this);

//        //加料重量
//        feed_weight = findViewById(R.id.feedWeight);
//        //养殖盒重量
//        breed_box_weight = findViewById(R.id.breed_box_weight);
        //目标重量
//        target_weight = findViewById(R.id.target_weight);
        //实际重量
//        reality_weight = findViewById(R.id.reality_weight);
        //培育盒重
        cultivate_box_weight = findViewById(R.id.cultivate_box_weight);
        //大虫及渣加盒重
        insect_residus_box_weight = findViewById(R.id.insect_residus_box_weight);
        //大虫及渣重量
//        insect_residus_weight = findViewById(R.id.insect_residus_weight);

        remark = findViewById(R.id.incoming_scene_remark);

        //如果甲方bb就先把这个注释掉
        deviceName_3.setEnabled(false);

//        weightChange_watcher = new TextWatcher()  {
//            @Override
//            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//                //这个方法被调用，说明在s字符串中，从start位置开始的count个字符即将被长度为after的新文本所取代。在这个方法里面改变s，会报错。
//            }
//            @Override
//            public void onTextChanged(CharSequence s, int start, int before, int count) {
//                //这个方法被调用，说明在s字符串中，从start位置开始的count个字符刚刚取代了长度为before的旧文本。在这个方法里面改变s，会报错。
//            }
//            @Override
//            public void afterTextChanged(Editable s) {
//                //这个方法被调用，那么说明s字符串的某个地方已经被改变。
//                String feed_weight_ = feed_weight.getText().toString().equals("")? "0.00" : feed_weight.getText().toString();
//                String breed_box_weight_ = breed_box_weight.getText().toString().equals("")? "0.00" : breed_box_weight.getText().toString();
//                String cultivate_box_weight_ = cultivate_box_weight.getText().toString().equals("")? "0.00" : cultivate_box_weight.getText().toString();
//                String target_weight_ = target_weight.getText().toString().equals("")? "0.00" : target_weight.getText().toString();
//                String insect_residus_box_weight_ = insect_residus_box_weight.getText().toString().equals("")? "0.00" : insect_residus_box_weight.getText().toString();
//                String insect_residus_weight_ = insect_residus_weight.getText().toString().equals("")? "0.00" : insect_residus_weight.getText().toString();
//
//                //四舍五入输入值再计算
//                float new_target_weight = new BigDecimal((Float.parseFloat(feed_weight_) + Float.parseFloat(breed_box_weight_)))
//                        .setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
//                target_weight.setText(new_target_weight+"");
//
//                float new_insect_residus_weight = new BigDecimal((Float.parseFloat(insect_residus_box_weight_)
//                        - Float.parseFloat(cultivate_box_weight_)))
//                        .setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
//                insect_residus_weight.setText(new_insect_residus_weight+"");
//            }
//        };
////        feed_weight.addTextChangedListener(weightChange_watcher);
////        breed_box_weight.addTextChangedListener(weightChange_watcher);
//        cultivate_box_weight.addTextChangedListener(weightChange_watcher);
//        insect_residus_box_weight.addTextChangedListener(weightChange_watcher);

        //获取待分离设备列表
        RequestQueue queue = Volley.newRequestQueue(this);
        String url2 = Config.url + "/research/feed/getList" + "?factory=" + factory;
        StringRequest stringRequest2 = new StringRequest(Request.Method.GET, url2,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            if (!jsonObject.isNull("data")) {
                                JSONArray data = jsonObject.getJSONArray("data");
                                if( data.length()>0){
                                    for (int i=0; i < data.length(); i++){
                                        JSONObject record = data.getJSONObject(i);
                                        batchGroupNumberList.add(new BatchGroupNumber(record.getInt("id"),record.getString("batch"),record.getString("zubie"),record.getString("boxNumber"),"",""));
                                        deviceNameList.add(record.getString("deviceName1"));
                                    }
                                    Log.d("batchGroupNumberList", batchGroupNumberList.toString());
                                    ArrayAdapter<BatchGroupNumber> adapter = new ArrayAdapter<BatchGroupNumber>(IncomingSceneFeed.this, android.R.layout.simple_spinner_item,batchGroupNumberList);
                                    batchGroupNumber.setAdapter(adapter);
                                    batchGroupNumber.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                                        @Override
                                        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                                            belongTo_id = batchGroupNumberList.get(position).id;
                                            deviceName_3.setSelection(position);
                                        }
                                        @Override
                                        public void onNothingSelected(AdapterView<?> parent) {
                                            belongTo_id = -1;
                                        }
                                    });
                                    batchGroupNumber.setSelection(0,true);

                                    ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(IncomingSceneFeed.this, android.R.layout.simple_spinner_item,deviceNameList);
                                    deviceName_3.setAdapter(adapter1);
                                    deviceName_3.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                                        @Override
                                        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                                            deviceName = deviceNameList.get(position);
                                        }
                                        @Override
                                        public void onNothingSelected(AdapterView<?> parent) {
                                            deviceName = "";
                                        }
                                    });
                                    deviceName_3.setSelection(0,true);
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(IncomingSceneFeed.this,
                        "获取信息失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
        stringRequest2.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue.add(stringRequest2);

//        // 获取设备名称
//        String url = Config.url + "/research/crush/getlast" + "?factory=" + factory;
//        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
//                new Response.Listener<String>() {
//                    @Override
//                    public void onResponse(String response) {
//                        try {
//                            JSONObject jsonObject = new JSONObject(response);
//                            Log.d("jy",response.toString());
//                            JSONObject data;
//                            if(jsonObject.get("data")!=null && !jsonObject.get("data").toString().equals("null")){
//                                data = jsonObject.getJSONObject("data");
//                                if (!data.isNull("id")) {
//
//                                    deviceNameList.add(data.getString("deviceName1"));
//                                    ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(IncomingSceneFeed.this, android.R.layout.simple_spinner_item,deviceNameList);
//                                    deviceName_3.setAdapter(adapter1);
//                                    deviceName_3.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
//                                        @Override
//                                        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//                                            deviceName = deviceNameList.get(position);
//                                        }
//                                        @Override
//                                        public void onNothingSelected(AdapterView<?> parent) {
//                                            deviceName = "";
//                                        }
//                                    });
//                                    deviceName_3.setSelection(0,true);
////                                    deviceName_2.setText();
//                                }
//                            }
//                        } catch (JSONException e) {
//                            e.printStackTrace();
//                        }
//                    }
//                }, new Response.ErrorListener() {
//            @Override
//            public void onErrorResponse(VolleyError error) {
//                Toast.makeText(IncomingSceneFeed.this,
//                        "获取设备名称失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
//            }
//        });
//        stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
//                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
//        queue.add(stringRequest);
    }
    /**
     * 提交内容并设置输入缓存
     * @param view
     */
    public void save(View view) {
        if (feed_start.getText().toString().equals("")) {
            Toast.makeText(this, "请填写进料开始时间", Toast.LENGTH_SHORT).show();
            return;
        }if (feed_end.getText().toString().equals("")) {
            Toast.makeText(this, "请填写进料结束时间", Toast.LENGTH_SHORT).show();
            return;
        }if (deviceName.equals("")) {
            Toast.makeText(this, "请填写设备名称", Toast.LENGTH_SHORT).show();
            return;
        }
//        if (feed_weight.getText().toString().equals("")) {
//            Toast.makeText(this, "请填写加料重量", Toast.LENGTH_SHORT).show();
//            return;
//        }
        if (cultivate_box_weight.getText().toString().equals("")) {
            Toast.makeText(this, "请填写培育盒重", Toast.LENGTH_SHORT).show();
            return;
        }if (income_weight.getText().toString().equals("")) {
            Toast.makeText(this, "请填写进料净重", Toast.LENGTH_SHORT).show();
            return;
        }if (insect_residus_box_weight.getText().toString().equals("")) {
            Toast.makeText(this, "请填写大虫及渣及盒重", Toast.LENGTH_SHORT).show();
            return;
//        }if (insect_residus_weight.getText().toString().equals("")) {
//            Toast.makeText(this, "请填写大虫及渣重", Toast.LENGTH_SHORT).show();
//            return;
        }
        new AlertDialog.Builder(this)
                .setTitle("确定保存吗？")
                .setCancelable(false)
                .setNegativeButton("取消", ((dialog, which) ->
                        Toast.makeText(this, "取消保存", Toast.LENGTH_SHORT).show()))
                .setPositiveButton("确定", (dialog, which) -> {

//                    double target_weight_value = Double.parseDouble(target_weight.getText().toString());
//                    double reality_weight_value = Double.parseDouble(reality_weight.getText().toString());
//                    if(target_weight_value != reality_weight_value){
//                        Toast.makeText(IncomingSceneFeed.this, "实际重量与目标重量不一致", Toast.LENGTH_SHORT).show();
//                    }else {
                    //提交请求
                    incomingDate = new Date(System.currentTimeMillis());
                    RequestQueue queue = Volley.newRequestQueue(this);
                    String url = Config.url + "/research/feed/add";
                    StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                            new Response.Listener<String>() {
                                @Override
                                public void onResponse(String response) {
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        String code = jsonObject.getString("code");
                                        if (code.startsWith("2")) {
                                            Toast.makeText(IncomingSceneFeed.this,
                                                    "保存成功", Toast.LENGTH_SHORT).show();
                                            Intent intent = getIntent();
                                            finish();
                                            startActivity(intent);
                                        }
                                        else
                                            Toast.makeText(IncomingSceneFeed.this,
                                                    "保存失败", Toast.LENGTH_SHORT).show();
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Toast.makeText(IncomingSceneFeed.this, "保存失败", Toast.LENGTH_SHORT).show();
                            Log.d("jy", error.toString());
                        }
                    }) {
                        @Override
                        protected Map<String, String> getParams() throws AuthFailureError {
                            Map<String, String> map=new HashMap<>();
//                            map.put("feedDate", simpleDateFormat.format(incomingDate));
//                            System.out.println("idid"+belongTo_id);
                            map.put("belongToId", belongTo_id+"");
                            map.put("deviceName3",  deviceName);
                            map.put("feedStarttime", feed_start.getText().toString());
                            map.put("feedEndtime", feed_end.getText().toString());
                            map.put("feedWeight", income_weight.getText().toString());
                            map.put("cultivateBoxWeight", cultivate_box_weight.getText().toString());
                            map.put("targetWeight", "0.0");
                            map.put("insectResidusBoxWeight", insect_residus_box_weight.getText().toString());
                            map.put("insectResidusWeight", "0.1");
                            map.put("recorder",name);
                            map.put("remark", ((TextView) findViewById(R.id.incoming_scene_remark)).getText().toString());
                            map.put("factory", factory);
                            return map;
                        }
                    };
                    stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                            DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                    queue.add(stringRequest);
//                    }
                })
                .show();
    }

    /**
     * 隐藏键盘
     */
    protected void hideInput() {
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        View v = getWindow().peekDecorView();
        if (null != v) {
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }
    }

    /**
     * 时间选择
     * @param activity
     * @param themeResId
     * @param tv
     * @param calendar
     */
    public static void showTimePickerDialog(Activity activity, int themeResId, final TextView tv, Calendar calendar) {
        // Calendar c = Calendar.getInstance();
        // 创建一个TimePickerDialog实例，并把它显示出来
        // 解释一哈，Activity是context的子类
        new TimePickerDialog( activity,themeResId,
                // 绑定监听器
                new TimePickerDialog.OnTimeSetListener() {
                    @Override
                    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                        tv.setText(String.format("%02d", hourOfDay) + ":" + String.format("%02d", minute));
                    }
                }
                // 设置初始时间
                , calendar.get(Calendar.HOUR_OF_DAY)
                , calendar.get(Calendar.MINUTE)
                // true表示采用24小时制
                ,true).show();
    }
    @Override
    public void onClick(View view) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
        switch (view.getId()) {
            case R.id.btn_feed_start:
                Date date_1_start = new Date(System.currentTimeMillis());
                String s_1_start = simpleDateFormat.format(date_1_start);
                feed_start.setText(s_1_start);
                btn_feed_start.setEnabled(false);
                break;
            case R.id.btn_feed_end:
                Date date_1_end = new Date(System.currentTimeMillis());
                String s_1_end = simpleDateFormat.format(date_1_end);
                feed_end.setText(s_1_end);
                btn_feed_end.setEnabled(false);
                break;
            case R.id.feed_start:
                showTimePickerDialog(this,  2, feed_start, calendar);;
                break;
            case R.id.feed_end:
                showTimePickerDialog(this,  2, feed_end, calendar);;
                break;
            default:
                break;
        }
    }

    /**
     * 称重接口
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        String weight = data.getStringExtra("weight");
        switch (activeButton){
//            case "breed_boxWeight_btn":
//                breed_box_weight.setText(weight);
//                break;
            case "realityWeight_btn":
                income_weight.setText(weight);
                break;
            case "cultivate_boxWeight_btn":
                cultivate_box_weight.setText(weight);
                break;
            case "insectResidusBoxWeight_btn":
                insect_residus_box_weight.setText(weight);
                break;
        }
    }
    public void goWeight(View view) {
        switch (view.getId()) {
//            case R.id.breed_boxWeight_btn:
//                activeButton = "breed_boxWeight_btn";
//                break;
            case R.id.realityWeight_btn:
                activeButton = "realityWeight_btn";
                break;
            case R.id.cultivate_boxWeight_btn:
                activeButton = "cultivate_boxWeight_btn";
                break;
            case R.id.insectResidusBoxWeight_btn:
                activeButton = "insectResidusBoxWeight_btn";
                break;
            default:
                break;
        }
        Intent intent = new Intent(IncomingSceneFeed.this, WeightActivity.class);
        startActivityForResult(intent, 1);
    }
}